package juc;

import org.junit.Test;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class LinkedBlockingQueueTest {

	@Test
	public void test() throws InterruptedException {
		final BlockingQueue blockingQueue = new LinkedBlockingQueue(10);
		// 新建两个生产者线程+一个消费者线程，（生产是比消费快的，当缓冲区满时，生产者会阻塞）
		Thread t1 = new Thread(new Producer(blockingQueue), "生产者1");
		Thread t2 = new Thread(new Producer(blockingQueue), "生产者2");
		Thread t3 = new Thread(new Consumer(blockingQueue), "消费者1");
		t1.start();
		t2.start();
		t3.start();
		t1.join();
		t2.join();
		t3.join();
	}

	class Consumer implements Runnable {

		private BlockingQueue blockingQueue;

		Consumer(BlockingQueue blockingQueue) {
			this.blockingQueue = blockingQueue;
		}

		@Override
		public void run() {
			for (; ; ) {
				System.out.println(Thread.currentThread().getName() + "消费,当前容量:" + blockingQueue.size());
				try {
					Thread.sleep(1000);
					blockingQueue.take();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	class Producer implements Runnable {

		private BlockingQueue blockingQueue;

		Producer(BlockingQueue blockingQueue) {
			this.blockingQueue = blockingQueue;
		}

		@Override
		public void run() {
			for (; ; ) {
				System.out.println(Thread.currentThread().getName() + "生产,当前容量:" + blockingQueue.size());
				try {
					Thread.sleep(1000);
					blockingQueue.put("product");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
